#!/usr/bin/env bash

environment_variable()
{
    local split="------------------------------"

    echo "环境变量"
    echo $split

    echo $HOSTNAME
    echo $PWD
    cd /etc
    echo $PWD
    cd -

# MACHTYPE = HOSTTYPE - company - OSTYPE
    echo $OSTYPE        # 操作系统
    echo $MACHTYPE      # cpu-company-system
    echo $HOSTTYPE      # 机器类型
}

path()
{
    local split="------------------------------"

    echo "路径"
    echo $split

    echo '$0: '$0
    echo 'readlink -e: '$(readlink -e $0)
    echo 'realpath: '$(realpath $0)
}

local_variable()
{
    local split="------------------------------"

    echo "局部变量"
    echo $split

    for ((i=0; i<10; i++))
    do
        echo $i
    done

    i=0
    while ((i<10))
    do
        echo $i
        (( i++ ))
    done

    echo $split

    local is_true=0
    if (( is_true ))
    then
        echo "$is_true is true"
    else
        echo "$is_true is false"
    fi

    echo $split

    local a=101
    local mod=3
    local b=$((( a%mod != 0 ? a%mod : mod )))
    echo "$a % $mod = $b"
}

random()
{
    local split="------------------------------"

    echo "随机数"
    echo $split

    echo "[0, 32768): "$RANDOM

    echo $split

    echo "[20-100): "
    for i in {1..10}
    do
        (( r=(RANDOM % (100-20)) + 20 ))
        echo "    "$r
    done
}

here-document()
{
    local split="------------------------------"

    echo "立即文档"
    echo $split

    local doc="abc"

    cat <<EOF
    $doc
    \$doc
EOF

    echo $split

    cat <<'EOF'
    $doc
    \$doc
EOF

    echo $split

    echo "变量扩展为标准输入"
    echo

    cat <<<$HOSTNAME

    echo

    while read line
    do
        echo $line
    done <<<$HOSTNAME

    echo

    local s="a:100 b:200"
    echo "$s --> $(sed 's/:/=/g' <<<$s)"
}

main()
{
    local split="========================================"

    echo $split

    environment_variable
    echo $split

    local_variable
    echo $split

    random
    echo $split

    here-document
    echo $split

    path
    echo $split
}

main
exit $?
